/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.ipfw.cs590.cheat.struts.actions;

import edu.ipfw.cs590.cheat.AssignmentManagementInterface;
import edu.ipfw.cs590.cheat.AssignmentManagementService;
import edu.ipfw.cs590.cheat.struts.actionforms.ViewAssignmentForm;
import edu.ipfw.cs590.cheat.util.Authentication;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.web_cat._1_0.assignment_sharing.Assignment;

/**
 *
 * @author safar
 */
public class ViewAssignment extends Action {

    /* forward name="success" path="" */
    private final static String SUCCESS = "ViewSuccess";
    private final static String FAILURE = "ViewFailure";

    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        if (form instanceof ViewAssignmentForm) {
            ViewAssignmentForm vaf = (ViewAssignmentForm) form;

            try {
                // Call Web Service Operation
                AssignmentManagementService service = new AssignmentManagementService();
                AssignmentManagementInterface port = service.getAssignmentManagementSOAP();

                //Call service
                Assignment result = port.getAssignmentMetadata(request.getParameter("id"));

                //Get the assignment
                if (result != null) {
                    //Get the assignments history
                    vaf.setAssignmentHistory(
                            getHistory(request.getSession(false), result));

                    vaf.setIsOwner(getOwnerStatus(request.getSession(false), result));

                    //Store the assignment
                    vaf.setAssignment(result);

                    //Return GOOOOOOOD
                    return mapping.findForward(SUCCESS);
                }
            } catch (Exception exc) {
                //Something bad happened on the webservice side fail.
                ActionMessages errors = new ActionMessages();
                errors.add(ActionMessages.GLOBAL_MESSAGE,
                        new ActionMessage("errors.service.error", "View Assignment", exc.getMessage()));
                this.saveErrors(request, errors);

                //Return failure.
                return mapping.getInputForward();
            }
        }

        //Something bad happened on the webservice side fail.
        ActionMessages errors = new ActionMessages();
        errors.add(ActionMessages.GLOBAL_MESSAGE,
                new ActionMessage("error.form.invalid"));
        this.saveErrors(request, errors);

        return mapping.getInputForward();
    }

    /**
     * Get the history for this assignment.
     * @param session session.
     * @param child assignment that will be the child in history.
     * @return List<Assignment> list of historical assignments in order.
     */
    private List<Assignment> getHistory(HttpSession session, Assignment child) {

        try { // Call Web Service Operation
            AssignmentManagementService service = new AssignmentManagementService();
            AssignmentManagementInterface port = service.getAssignmentManagementSOAP();

            //Get the history
            return port.getAssignmentHistory(child.getRepository().getUuid());
        } catch (Exception ex) {
            return new ArrayList<Assignment>();
        }
    }

    /**
     * Get the owner status.
     * @param session session.
     * @param assign assignment.
     * @return boolean true if owner, false otherwise.
     */
    private boolean getOwnerStatus(HttpSession session, Assignment assign) {

        try {
            // Call Web Service Operation
            AssignmentManagementService service = new AssignmentManagementService();
            AssignmentManagementInterface port = service.getAssignmentManagementSOAP();

            //return status
            return ((String) session.getAttribute(Authentication.SESSION_NAME_EMAIL)).equalsIgnoreCase(port.getAssignmentOwner(assign.getRepository().getUuid()));
        } catch (Exception ex) {
            return false;
        }
    }
}
